/*
Derived HTML.
Copyright (C) 2009 dhudson@pushtechnology.com

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/


package org.dhtml;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.StringWriter;

public class Utils {

    /**
     * Reads the entire contents of a file into a String.
     * <P>
     * 
     * @param file the file to read.
     * 
     * @return a string containing the entire file content.
     * 
     * @throws DHTMLException if unable to read the file.
     */
    public static String readFileAsString(File file) throws DHTMLException {

        if (file==null) {
            throw new DHTMLException("Null file parameter");
        }

        if (!file.exists()) {
            throw new DHTMLException("File ["
                +file.getAbsolutePath()
                +"] does not exist");
        }

        if (!file.canRead()) {
            throw new DHTMLException("Unable to read file ["
                +file.getAbsolutePath()
                +"]");
        }

        try {
            char data[] = new char[(int)file.length()];
            BufferedReader reader = new BufferedReader(new FileReader(file));

            int index = reader.read(data);

            reader.close();
            String retString = new String(data,0,index);

            return retString;
        }
        catch (Exception ex) {
            throw new DHTMLException("Unable to read file "+file,ex);
        }
    }

    /**
     * getThrowableInfo
     * 
     * @param message
     * @param t
     * @return a string containing the throwable information
     */
    public static String getThrowableInfo(String message,Throwable t) {
        if (t==null) {
            return message;
        }

        StringBuilder buffer = new StringBuilder(message);
        buffer.append("\nStack Trace:\n");
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        t.printStackTrace(printWriter);
        buffer.append(stringWriter.toString());
        return buffer.toString();
    }
}
